package com.api.shopapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.common.HttpClientUtil;
import com.api.shopapi.entity.*;
import com.api.shopapi.service.ElderlyService;
import com.api.shopapi.service.StaffService;
import com.api.shopapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;


//delete

@RequestMapping("Positioning")
@RestController
public class PositioningController extends BaseController {

    //定位老人
    @RequestMapping(value = "PositioningForElderly", method = RequestMethod.POST)
    public MyResult PositioningForElderly(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/PositioningForElderly");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/PositioningForElderly";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONObject("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/PositioningForElderly", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }


    }

    //围栏详情
    @RequestMapping(value = "WeiLanInfo", method = RequestMethod.POST)
    public MyResult WeiLanInfo(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String userDeviceCode = jsonObject.getString("userDeviceCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/WeiLanInfo");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/WeiLanInfo";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONObject("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/WeiLanInfo", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //电子围栏（添加 修改  报警信息修改）
    @RequestMapping(value = "WeiLan", method = RequestMethod.POST)
    public MyResult WeiLan(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String userDeviceCode = jsonObject.getString("userDeviceCode");
            String lat = jsonObject.getString("lat");
            String lon = jsonObject.getString("lon");
            String distance = jsonObject.getString("distance");
            String alertType = jsonObject.getString("alertType");
            String address = jsonObject.getString("address");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/WeiLan");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/WeiLan";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("lat",lat);
            map.put("lon",lon);
            map.put("distance",distance);
            map.put("alertType",alertType);
            map.put("address",address);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONObject("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/WeiLan", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //运动轨迹
    @RequestMapping(value = "MotionCurve", method = RequestMethod.POST)
    public MyResult MotionCurve(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String startTime = jsonObject.getString("startTime");
            String endTime = jsonObject.getString("endTime");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/MotionCurve");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/MotionCurve";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONArray("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/MotionCurve", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //获取SOS手机列表
    @RequestMapping(value = "ListSOSContacts", method = RequestMethod.POST)
    public MyResult ListSOSContacts(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/ListSOSContacts");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/ListSOSContacts";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONArray("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/ListSOSContacts", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //修改SOS联系人
    @RequestMapping(value = "EditSOSContacts", method = RequestMethod.POST)
    public MyResult EditSOSContacts(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");
            JSONArray phones = jsonObject.getJSONArray("phones");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/EditSOSContacts");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/EditSOSContacts";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("phones",phones);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONObject("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/EditSOSContacts", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }


    }

    //获取白名单手机列表
    @RequestMapping(value = "ListWhiteContacts", method = RequestMethod.POST)
    public MyResult ListWhiteContacts(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/ListWhiteContacts");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/ListWhiteContacts";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONArray("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/ListWhiteContacts", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //编辑白名单手机列表
    @RequestMapping(value = "EditWhiteContacts", method = RequestMethod.POST)
    public MyResult EditWhiteContacts(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");
            JSONArray phones = jsonObject.getJSONArray("phones");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/EditWhiteContacts");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/EditWhiteContacts";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("phones",phones);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONObject("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/EditWhiteContacts", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //围栏详情（设置围栏是否报警）
    @RequestMapping(value = "WeiLanInfoDevice", method = RequestMethod.POST)
    public MyResult WeiLanInfoDevice(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String userDeviceCode = jsonObject.getString("userDeviceCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/WeiLanInfoDevice");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/WeiLanInfoDevice";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONObject("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/WeiLanInfoDevice", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //修改围栏是否报警
    @RequestMapping(value = "EditIsAlert", method = RequestMethod.POST)
    public MyResult EditIsAlert(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");
            int alertSwitch = jsonObject.getInteger("alertSwitch");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/EditIsAlert");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String url=deviceApi+"/Positioning/EditIsAlert";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("alertSwitch",alertSwitch);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONObject("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/EditIsAlert", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //查看报警信息
    @RequestMapping(value = "ListBaoJingByPhone",method = RequestMethod.POST)
    public MyResult ListBaoJingByPhone(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            int pageIndex =jsonObject.getInteger("pageIndex");
            int pageSize =jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/ListBaoJingByPhone");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            String url=deviceApi+"/Positioning/ListBaoJingByPhone";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("pageIndex",pageIndex);
            map.put("pageSize",pageSize);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONArray("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/ListBaoJingByPhone", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }




    //查看血压
    @RequestMapping(value = "ListBloodByUserDeviceCode",method = RequestMethod.POST)
    public MyResult ListBloodByUserDeviceCode(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            int pageIndex =jsonObject.getInteger("pageIndex");
            int pageSize =jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/ListBloodByUserDeviceCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            String url=deviceApi+"/Positioning/ListBloodByUserDeviceCode";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("pageIndex",pageIndex);
            map.put("pageSize",pageSize);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONArray("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/ListBloodByUserDeviceCode", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //查看心率
    @RequestMapping(value = "ListHeartByUserDeviceCode",method = RequestMethod.POST)
    public MyResult ListHeartByUserDeviceCode(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            int pageIndex =jsonObject.getInteger("pageIndex");
            int pageSize =jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/ListHeartByUserDeviceCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            String url=deviceApi+"/Positioning/ListHeartByUserDeviceCode";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("pageIndex",pageIndex);
            map.put("pageSize",pageSize);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONArray("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/ListHeartByUserDeviceCode", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //查看血氧
    @RequestMapping(value = "ListOxygenByUserDeviceCode",method = RequestMethod.POST)
    public MyResult ListOxygenByUserDeviceCode(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String userDeviceCode = jsonObject.getString("userDeviceCode");

            int pageIndex =jsonObject.getInteger("pageIndex");
            int pageSize =jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Positioning/ListOxygenByUserDeviceCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            String url=deviceApi+"/Positioning/ListOxygenByUserDeviceCode";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userDeviceCode",userDeviceCode);
            map.put("pageIndex",pageIndex);
            map.put("pageSize",pageSize);
            String json = postTemplate(url, map);
            JSONObject jsonObject1 = JSONObject.parseObject(json);
            int error = jsonObject1.getIntValue("error");
            if (error==0){
                return success(jsonObject1.getJSONArray("data"));
            }else {
                return failed(jsonObject1.getString("message"));
            }
        } catch (Exception e) {
            insertError("/Positioning/ListOxygenByUserDeviceCode", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }






    //百度转腾讯
    private static final double xPi = 3.14159265358979324 * 3000.0 / 180.0;

    public static Map<String, Double> bdDecrypt(String lon, String lan) {
        double x = Double.valueOf(lon) - 0.0065, y = Double.valueOf(lan) - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * xPi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * xPi);
        double ggLon = z * Math.cos(theta);
        double ggLat = z * Math.sin(theta);
        Map<String, Double> bdMap = new HashMap<String, Double>();
        bdMap.put("lon", ggLon);
        bdMap.put("lat", ggLat);
        return bdMap;
    }

    //百度转高德（百度坐标bd09ll–>火星坐标gcj02ll）
    private double[] bdToGaoDe(double bd_lat, double bd_lon) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }

    //高德转百度（火星坐标gcj02ll–>百度坐标bd09ll）
    private double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }

    //判断时间是不是在范围之内
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {

            return true;
        } else {
            return false;
        }
    }


}
